import json
import os
import shutil
import pandas as pd
from json_to_jpg import deal_output_json_log
from utils import get_direct_subdirectories, get_files_containing_substring


def csv_to_list(path):
    # 示例数据
    df = pd.read_csv(path)
    df_data = df.to_dict(orient='records')
    # 创建一个空列表用于保存所有记录
    all_records = []
    # 定义门架ID
    gantry_a_id = os.path.basename(path).split('.')[0].split('-')[1]
    gantry_b_id = os.path.basename(path).split('.')[0].split('-')[2]

    # gantry_a_id = os.path.basename(path).split('.')[0][4:].split(',')[0]
    # gantry_b_id = os.path.basename(path).split('.')[0][4:].split(',')[1].split('-')[0]

    # 遍历每一行数据
    for row in df_data:
        vlp = row['vlp']
        feevehicletype = row['feevehicletype']
        # 如果有经过门架A的时间，则添加一条记录
        if pd.notna(row['transtime_up']):
            transtime = pd.to_datetime(row['transtime_up'], format='%Y/%m/%d %H:%M:%S')
            record = {'gantry_id': gantry_a_id, 'vlp': vlp, 'feevehicletype': feevehicletype, 'transtime': transtime}
            all_records.append(record)

        # 如果有经过门架B的时间，则添加一条记录
        if pd.notna(row['transtime_down']):
            transtime = pd.to_datetime(row['transtime_down'], format='%Y/%m/%d %H:%M:%S')
            record = {'gantry_id': gantry_b_id, 'vlp': vlp, 'feevehicletype': feevehicletype, 'transtime': transtime}
            all_records.append(record)

    # 按照过车时间对记录进行排序
    all_records_sorted = sorted(all_records, key=lambda x: x['transtime'])
    return all_records_sorted


def save_json_for_csv(path, json_path):
    if not os.path.exists(json_path):
        os.makedirs(json_path)
    csv_path = get_files_containing_substring(path, 'all_')
    all_records_sorted = csv_to_list(csv_path)
    old_name = os.path.basename(csv_path).split('.')[0]
    # new_file = "all_" + old_name.split('-')[1] + "-" + old_name.split('-')[0][4:].split(',')[0] + '-' + old_name.split('-')[0][4:].split(',')[1]
    new_path = os.path.join(json_path, old_name + '.json')
    with open(new_path, 'w', encoding='utf-8') as f:
        for row in all_records_sorted:
            row['transtime'] = row['transtime'].strftime('%Y-%m-%d %H:%M:%S')
            json.dump(row, f, ensure_ascii=False)
            f.write('\n')


def write_json(folder_path, result_path):
    result = {}
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if int(str(file)[4:12]) >= 20230101:
                file_path = os.path.join(root, file)  # 获取完整文件路径
                print("2025:", file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    index = 0
                    for line in f:
                        index += 1
                        data_json = json.loads(line.strip())
                        data_json['gantry_id'] = data_json['gantry_id'] + "_" + str(file).split('.')[0]
                        if index not in result.keys():
                            result[index] = [data_json]
                        else:
                            result[index].append(data_json)
            else:
                file_path = os.path.join(root, file)  # 获取完整文件路径
                print("2024:", file)
                with open(file_path, 'r', encoding='utf-8') as ff:
                    data = ff.read()
                    data_json = json.loads(data)
                    for index, data_one in enumerate(data_json):
                        if index not in result.keys():
                            data_one['gantry_id'] = data_one['gantry_id'] + "_" + str(file).split('.')[0]
                            result[index] = [data_one]
                        else:
                            data_one['gantry_id'] = data_one['gantry_id'] + "_" + str(file).split('.')[0]
                            result[index].append(data_one)
    if not os.path.exists(os.path.dirname(result_path)):
        os.makedirs(os.path.dirname(result_path))
    with open(result_path, 'w', encoding='utf-8') as file_w:
        for k, v in result.items():
            file_w.write(str(v).replace("'", '"') + "\n")


def get_all_config_json(d_path, folder_B):
    for dir_path in get_direct_subdirectories(d_path):
        # 定义文件夹 A、B 和 C 的路径
        folder_A = dir_path
        # 创建文件夹 B 和 C（如果不存在）
        if not os.path.exists(folder_B):
            os.makedirs(folder_B)

        # 获取文件夹 A 的名称（不包含路径）
        folder_A_name = os.path.basename(folder_A)
        # 生成对应的 JSON 文件名
        json_filename = f"{folder_A_name}.json"
        # 构建 JSON 文件的源路径
        source_json_path = os.path.join(folder_A, json_filename)
        # 检查该 JSON 文件是否存在
        if os.path.exists(source_json_path):
            # 构建 JSON 文件的目标路径
            destination_json_path = os.path.join(folder_B, json_filename)
            # 复制 JSON 文件
            shutil.copy2(source_json_path, destination_json_path)


def get_some_config_json(folder_path, old_path, folder_B):
    if not os.path.exists(folder_B):
        os.makedirs(folder_B)
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            name = file[4:]
            source_json_path = os.path.join(old_path, name)
            # 检查该 JSON 文件是否存在
            if os.path.exists(source_json_path):
                # 构建 JSON 文件的目标路径
                destination_json_path = os.path.join(folder_B, name)
                # 复制 JSON 文件
                shutil.copy2(source_json_path, destination_json_path)
            else:
                print(f"JSON 文件 {source_json_path} 不存在")


if __name__ == '__main__':
    # 获取离线文件的区间数据作为在线跑批算法的数据输入

    # 离线处理后的文件路径
    offline_folders_path = r"D:\GJ\项目\事故检测\output0321\output"
    # 按天存储所有日期的json文件的路径 all_开头的json
    all_json_path = r"D:\GJ\项目\事故检测\output0321\all_json"
    # 将100天数据组成数据列表，进行快速的算法跑批输入
    result_json_path = r'D:\GJ\项目\事故检测\output0321\result\result_20250324.json'
    # 存储所有区间配置参数的路径
    all_filename_json_path = r'D:\GJ\项目\事故检测\output0321\config\all_config'
    # 存储所需要的部分区间配置参数的路径
    some_filename_path = r"D:\GJ\项目\事故检测\output0321\config\some_config_1"

    # # 遍历所有文件夹，将csv文件转换为json文件
    # for dir_path in get_direct_subdirectories(offline_folders_path):
    #     if os.path.exists(os.path.join(dir_path, 'png')):
    #         save_json_for_csv(dir_path, all_json_path)
    #
    # # 将多个json文件合成一个json文件
    # write_json(all_json_path, result_json_path)
    #
    # # 将所有区间的参数配置json文件放到同一路径下 all_filename_json_path
    # get_all_config_json(offline_folders_path, all_filename_json_path)
    #
    # # 从all_filename_json_path中获取指定区间all_json_path的参数配置json文件放到同一路径下 some_filename_path
    # # get_some_config_json(all_json_path, all_filename_json_path, some_filename_path)


    # 在线跑批算法输出处理

    # 每个区间的在线跑批输出json文件路径
    folder = r'D:\GJ\项目\事故检测\output0311\0324\2025-03-24_15-17-37'
    # 保存位置，在该位置下新建三个文件夹，分别为save_csv、save_csv_1、save_png
    ppath = r'D:\GJ\项目\事故检测\output0311\0324'
    print(ppath)
    deal_output_json_log(folder, ppath)